﻿using System.Windows;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Diagnostics;
using ShanNiang.Hosting;
using System.Reflection;
using ShanNiang.AutoUpdate.Service;
using System.Configuration;
using System.IO;
using Microsoft.Extensions.Configuration;
using Serilog;
using ShanNiang.AutoUpdate.Service.Implementations;
using ShanNiang.AutoUpdate.Service.Interfaces;
using Microsoft.Extensions.Logging;
using ShanNiang.AutoUpdate.Service.Responses;

namespace ShanNiang.AutoUpdate
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        [STAThread]
        static void Main(string[] args)
        {
            using var host = CreateHostBuilder(args).Build();
            host.Start();
            //var checkSerice = host.Services.GetRequiredService<ICheckVersionService>();
            //var autoUpdateConfig = host.Services.GetRequiredService<AutoUpdateConfig>();
            //if (checkSerice.NeedToUpdate(out PublishedClientResponse? response))
            //{
            //Process.GetProcessesByName(autoUpdateConfig.MainProcessName).ToList().ForEach(p => p.Kill());
            var viewModel = host.Services.GetRequiredService<MainWindowViewModel>();
            //viewModel.RemoteClientResponse = response;
            var app = new App();
            app.InitializeComponent();
            app.MainWindow = host.Services.GetRequiredService<MainWindow>();
            app.MainWindow.Show();
            app.Run();
            // }
        }
        /// <summary>
        /// 创建和配置主机
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        static IHostBuilder CreateHostBuilder(string[] args)
        {
            var hostBuilder = Host.CreateDefaultBuilder(args);
            hostBuilder.ConfigureAppConfiguration(HostingExtensions.UseConfiguration);
            hostBuilder.ConfigureServices((context, services) =>
            {
                //加载默认窗体和默认服务
                //加载本地服务
                services.AddLocalServices(context.Configuration, typeof(MainWindow).Assembly);
                //添加本地窗体
                services.AddLocalWindows(context.Configuration, typeof(MainWindow).Assembly);
                //添加viewModel
                services.AddSingleton<MainWindowViewModel>();
                //添加配置信息
                services.AddSingleton(context.Configuration.GetSection("AutoUpdateConfig").Get<AutoUpdateConfig>() ?? new AutoUpdateConfig());
                //services.Configure<AutoUpdateConfig>(context.Configuration.GetSection("AutoUpdateConfig"));
            });
            hostBuilder.UseSerilog((ctx, lc) => lc.ReadFrom.Configuration(ctx.Configuration));
            return hostBuilder;
        }

        //static bool CheckUpdate(ICheckVersionService checkVersionService)
        //{
        //    return checkVersionService.NeedToUpdate();
        //    //if (checkVersionService.CheckVersion())
        //    //{ 
        //    //    Process.GetProcessesByName(autoUpdateConfig.MainProcessName).ToList().ForEach(p => p.Kill());
        //    //}
        //    ////如果本地版本足够新
        //    //if (remoteClientResponse != null && remoteClientResponse.RemoteVersion.CompareTo(localVersion) <= 0)
        //    //{
        //    //    Environment.Exit(0);
        //    //}
        //    //else
        //    //{
        //    //    Loaded += Window_Loaded;
        //    //    //Process.Start(new ProcessStartInfo("pwsh") { UseShellExecute = true });
        //    //}
        //}

        ///// <summary>
        ///// 服务实现程序集名称
        ///// </summary>
        //public const string LocalServiceAssemblyName = "ShanNiang.AutoUpdate";
        ///// <summary>
        ///// windows 程序集名称
        ///// </summary>
        //public const string LocalWindowsAssemblyName = "ShanNiang.AutoUpdate";


        //static App()
        //{
        //    var hostBuilder = Host.CreateDefaultBuilder();
        //    var windwosAssembly = Assembly.Load(LocalWindowsAssemblyName);
        //    var servicesAssembly = Assembly.Load(LocalServiceAssemblyName);
        //    //hostBuilder.ConfigureHostConfiguration(HostingExtensions.UseConfiguration);
        //    hostBuilder.ConfigureAppConfiguration(HostingExtensions.UseConfiguration);
        //    hostBuilder.UseSerilog((ctx, lc) => lc
        //            .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}")
        //            .Enrich.FromLogContext()
        //            .ReadFrom.Configuration(ctx.Configuration));
        //    hostBuilder.ConfigureServices((context, services) => 
        //    { 
        //        //加载默认窗体和默认服务
        //        HostingExtensions.ConfigureServices(context, services, windwosAssembly, servicesAssembly);
        //        //配置其他服务
        //        services.Configure<AutoUpdateConfig>(context.Configuration.GetSection("AutoUpdateConfig"));
        //    });
        //    CurrentHost = hostBuilder.Build();
        //}
        ///// <summary>
        ///// 主机
        ///// </summary>
        //public static IHost CurrentHost { get; private set; }


        //protected override void OnStartup(StartupEventArgs e)
        //{
        //    CurrentHost.Start();
        //    base.OnStartup(e);
        //    var mainWindow = CurrentHost.Services.GetRequiredService<MainWindow>();
        //    mainWindow.Show();
        //}
    }
}
